/**
 * 高级日志记录模块 - 使用Winston实现
 * 支持控制台输出和文件存储
 */

const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const path = require('path');
const fs = require('fs');

// 确保日志目录存在
const logsDir = path.join(__dirname, '../../logs');
const appLogsDir = path.join(logsDir, 'app');
const monitorLogsDir = path.join(logsDir, 'monitor');
const systemLogsDir = path.join(logsDir, 'system');

[logsDir, appLogsDir, monitorLogsDir, systemLogsDir].forEach(dir => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
});

// 自定义日志格式
const customFormat = winston.format.combine(
  winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
  winston.format.printf(({ level, message, timestamp, category }) => {
    return `[${timestamp}] [${level.toUpperCase()}] ${category ? `[${category}] ` : ''}${message}`;
  })
);

// 创建不同类型的日志传输配置
function createLogger(category) {
  // 确定日志文件路径
  let logDir = appLogsDir;
  if (category === 'monitor') {
    logDir = monitorLogsDir;
  } else if (category === 'system') {
    logDir = systemLogsDir;
  }

  // 创建日志传输器
  const fileTransport = new DailyRotateFile({
    dirname: logDir,
    filename: `%DATE%.log`,
    datePattern: 'YYYY-MM-DD',
    zippedArchive: true,
    maxSize: '20m',
    maxFiles: '14d',
    level: 'info'
  });

  const errorFileTransport = new DailyRotateFile({
    dirname: logDir,
    filename: `%DATE%-error.log`,
    datePattern: 'YYYY-MM-DD',
    zippedArchive: true,
    maxSize: '20m',
    maxFiles: '30d', 
    level: 'error'
  });

  const consoleTransport = new winston.transports.Console({
    level: 'debug'
  });

  // 创建Winston记录器
  return winston.createLogger({
    levels: winston.config.npm.levels,
    format: customFormat,
    defaultMeta: { category },
    transports: [
      fileTransport,
      errorFileTransport,
      consoleTransport
    ]
  });
}

// 默认日志记录器
const defaultLogger = createLogger('app');
const monitorLogger = createLogger('monitor');
const systemLogger = createLogger('system');

// 通用日志函数
function logWithCategory(category, level, ...args) {
  let logger;
  if (category === 'monitor') {
    logger = monitorLogger;
  } else if (category === 'system') {
    logger = systemLogger;
  } else {
    logger = defaultLogger;
  }

  // 将多个参数转换为单个消息字符串
  const message = args.map(arg => 
    typeof arg === 'object' ? JSON.stringify(arg) : arg
  ).join(' ');

  logger.log(level, message);
}

// 导出的日志函数
const logger = {
  debug: (...args) => logWithCategory('app', 'debug', ...args),
  info: (...args) => logWithCategory('app', 'info', ...args),
  warn: (...args) => logWithCategory('app', 'warn', ...args),
  error: (...args) => logWithCategory('app', 'error', ...args),
  log: (...args) => logWithCategory('app', 'info', ...args),
  
  // 系统日志
  system: {
    debug: (...args) => logWithCategory('system', 'debug', ...args),
    info: (...args) => logWithCategory('system', 'info', ...args),
    warn: (...args) => logWithCategory('system', 'warn', ...args),
    error: (...args) => logWithCategory('system', 'error', ...args),
  },
  
  // 监控日志
  monitor: {
    debug: (...args) => logWithCategory('monitor', 'debug', ...args),
    info: (...args) => logWithCategory('monitor', 'info', ...args),
    warn: (...args) => logWithCategory('monitor', 'warn', ...args),
    error: (...args) => logWithCategory('monitor', 'error', ...args),
  }
};

module.exports = logger; 